package com.suneee.refund.address.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.context.page.Page;
import com.suneee.context.page.Sort;
import com.suneee.context.page.Sort.Order;
import com.suneee.core.util.StringUtils;
import com.suneee.orm.GenericDao;
import com.suneee.orm.util.WhereClauseBuilder;
import com.suneee.refund.address.bean.RefundAddress;
import com.suneee.refund.address.bean.RefundAddressSearchBean;
import com.suneee.refund.address.dao.RefundAddressDao;

@Repository("refundAddressDao")
public class RefundAddressDaoImpl extends GenericDao<RefundAddress, Long>implements RefundAddressDao {

	@Override
	@Transactional
	public void isDefaultById(Long id, String enterpriseCode,Integer shopId) 
	{
	Object [] args = {enterpriseCode,shopId};
	
	this.executeUpdate("update t_refund_address set is_default = 0 where   enterprise_code = ? and shop_id = ?", args);
	
	Object [] args1 = {enterpriseCode,shopId,id};
	this.executeUpdate("update t_refund_address set is_default = 1 where   enterprise_code = ? and shop_id = ? and id = ?", args1);
	
		/*StringBuffer SQL = new StringBuffer();
		SQL.append("update t_refund_address set ");
		SQL.append(" is_default = ? ");
		SQL.append(" where 1=1 and enterprise_code = ? and shop_id = ? ");
		Object[] argr = new Object[]{false,enterpriseCode,shopId};
		this.executeUpdate(SQL.toString(), argr);

		StringBuffer sql = new StringBuffer();
		sql.append("update t_refund_address set ");
		sql.append(" is_default = ? ");
		sql.append(" where id=? and enterprise_code = ?");
		Object[] arg = new Object[]{true,id,enterpriseCode};
		this.executeUpdate(sql.toString(), arg);*/

	}

	@Override
	public Page<RefundAddress> refundAddressList(RefundAddressSearchBean bean) {
		WhereClauseBuilder builder = new WhereClauseBuilder();
		builder.equals("enterprise_code", bean.getEnterpriseCode());
		builder.equals("shop_id", bean.getShopId());
		bean.setPageNumber(bean.getPageNumber() == 0 ? 1 : bean.getPageNumber());
		bean.setPageSize(bean.getPageSize() == 0 ? 10 : bean.getPageSize());
		bean.setSort((bean.getSort() == null || StringUtils.isEmpty(bean.getSort().getOrderByClause()))
				? new Sort("id", Order.DESC) : bean.getSort());
		Page<RefundAddress> page = selectWhere(builder.getSql(), bean, builder.getArgs());
		return page;

	}

	@Override
	public boolean existsId(Integer id) {
		List<RefundAddress> list = this.selectWhere("id = ? ", id);
		return list != null && list.size() > 0;
	}

	@Override
	public boolean exists(String enterpriseCode,Integer shopId) {
		Object[] args = new Object[]{enterpriseCode,shopId,true};
		List<RefundAddress> list = this.selectWhere(" enterprise_code = ? and shop_id = ? and is_default = ? ", args);
		return list != null && list.size() > 0;
	}
}